let express = require('express')
let formidable = require('formidable')
let mimeType = require('mime-types')
let fs = require("fs");
let path = require("path");
let bodyParser = require('body-parser');
//链接数据库
require('./model/index.js');
let User = require('./model/user.js')
let Obj = require('./model/obj.js')
let app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: true
}));

/*
 * 根据req.body的账号与后台匹配来判断是否登录
 */
app.get('/login', (req, res) => {
	res.setHeader('Access-Control-Allow-Origin', '*')

	User.findOne({
			username: req.query.username
		})
		.then(value => {
			if (value && value.password == req.query.password) {
				res.send(value)
			} else {
				res.send("");
			}
		})
		.catch(err => res.send(""))

})

//响应第一次options请求
app.options('*', (req, res) => {
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader("Access-Control-Allow-Headers", " *");
	res.send("hello")
})

app.post('/avatar', (req, res) => {
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader("Access-Control-Allow-Headers", " *");
	// console.log(req.body)
	// console.log(req);
	console.log(555)

	var form = new formidable.IncomingForm();
	form.parse(req, function(err, fields, files) {
		// console.log(req.body,789) 
		// console.log(files,456) 
		// res.send(files.file.path)   
		let filePath = path.resolve(files.file.name); // 原始文件地址
		let fileName = filePath.split('\\').slice(-1)[0].split('.'); // 提取文件名
		let fileMimeType = mimeType.lookup(filePath);
		//根据文件在你设备上的位置读取该文件的数据
		let data = fs.readFileSync(files.file.path);
		data = new Buffer.from(data).toString('base64');
		let base64 = 'data:' + fileMimeType + ';base64,' + data;
		//得到64编码的字符串并加上前缀
		// console.log(base64)
		res.send(base64)

	});

})

/* 
 * 接受来自req.body的username和password和sex
 * 并根据username的存在性决定是否创建用户账号
 */
app.post('/register', async (req, res) => {
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader("Access-Control-Allow-Headers", " *");
	
	await User.findOne({
			username: req.body.username
		})
		.then(value => {
			if (value) {
				res.send('该账户已存在')
			} else {
				return User.create({
					username: req.body.username,
					password: req.body.password,
					sex: req.body.sex == '男' ? 0 : 1
				})
			}
		})
		.then(value => {
			res.send("账号注册成功")
		})

})

/*
 * 接受来自req.body的修改信息，并根据数据库信息决定是否为其修改
 */
app.post('/modify', async (req, res) => {
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader("Access-Control-Allow-Headers", " *");
	
	//找到要修改的用户
	await User.findOne({
		_id: req.body._id
	}).then(value => {
		
		if (value && value.password == req.body.oldpassword) {
			//信息正确
			return User.where({
				username: req.body.username
			}).updateOne({
				avatar: req.body.avatar,
				sex: req.body.sex == "男" ? 0 : 1,
				password: req.body.password,
			})

		} else {
			//信息不正确，返回空
			res.send(null);
		}
	}).then(value => {
		res.send('ok')
	}).catch(err => {
		res.send(null)
	})
	
})

/*
 * 接收req.body里面的物品信息，并将物品与发布者关联
 */
app.post('/release', async (req, res) => {
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader("Access-Control-Allow-Headers", " *");
	
	await Obj.create({
		...req.body
	}).then(value => console.log('数据发布成功'))

	//获得新发布物品的id
	let objId;
	await Obj.findOne({
			objPublic: req.body.objPublic
		})
		.then(value => {
			objId = value._id
		})
	//获得发布者的以往发布的物品
	let objs = [];
	await User.findOne({
			_id: req.body.objPublic
		})
		.then(value => {
			objs = value.gainObjs;
			// console.log(value.gainObjs.length)
		})

	//添加发布者的物品（a polyfill，不知为何空数组里面会默认有一个不需要的空字符串值）
	if (objs.length == 1) {
		objs = [objId]
	} else {
		objs.push(objId)
	}

	//存储数据库
	await User.where({
		_id: req.body.objPublic
	}).updateOne({
		gainObjs: objs
	})

	res.send("ok")
})

app.listen(3000, () => {
	console.log("3000端口成功开启")
})
